<template>
  <div class="app-container">
    <!-- 搜索区域优化 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
        <el-form-item label="题目内容" prop="title">
          <el-input
            v-model="queryParams.title"
            placeholder="请输入题目内容关键字"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          >
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select 
            v-model="queryParams.categoryId" 
            placeholder="请选择或搜索分类" 
            clearable
            filterable
            remote
            :remote-method="handleCategorySearch"
            :loading="categoryLoading"
            style="width: 200px"
          >
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="typeId">
          <el-select 
            v-model="queryParams.typeId" 
            placeholder="请选择或搜索类型" 
            clearable
            filterable
            remote
            :remote-method="handleTypeSearch"
            :loading="typeLoading"
            style="width: 200px"
          >
            <el-option
              v-for="item in typeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="出题方" prop="creator">
          <el-input
            v-model="queryParams.creator"
            placeholder="请输入出题方"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域优化 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span class="card-title">题目列表</span>
        <div class="action-buttons">
          
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['question:questions:add']"
          >新增题目</el-button>
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['question:questions:edit']"
          >修改</el-button>
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['question:questions:remove']"
          >删除</el-button>
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['question:questions:export']"
          >导出</el-button>
          <el-button
            :type="showDeleted ? 'warning' : 'info'"
            plain
            icon="el-icon-delete"
            size="mini"
            @click="toggleRecycleBin"
          >{{ showDeleted ? '返回列表' : '回收站' }}</el-button>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </div>
      </div>

      <!-- 表格区域优化 -->
      <el-table
        v-loading="loading"
        :data="questionsList"
        @selection-change="handleSelectionChange"
        border
        stripe
        highlight-current-row
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="题目ID" align="center" prop="id" width="80" />
        <el-table-column label="题目内容" align="left" prop="title" :show-overflow-tooltip="true" min-width="300">
          <template slot-scope="scope">
            <div class="question-content" v-html="scope.row.title"></div>
          </template>
        </el-table-column>
        <el-table-column label="分类" align="center" prop="dtCategory.name" width="120" />
        <el-table-column label="类型" align="center" prop="dtQuestionType.name" width="120" />
        <el-table-column label="出题方" align="center" prop="creator" width="120" />
        <el-table-column label="状态" align="center" width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.isDeleted"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160">
          <template slot-scope="scope">
            <template v-if="!showDeleted">
              <!-- 正常列表的操作按钮 -->
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['question:questions:edit']"
              >修改</el-button>
              <el-divider direction="vertical"></el-divider>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['question:questions:remove']"
              >删除</el-button>
            </template>
            <template v-else>
              <!-- 回收站的操作按钮 -->
              <el-button
                size="mini"
                type="text"
                icon="el-icon-refresh"
                @click="handleRestore(scope.row)"
                v-hasPermi="['question:questions:edit']"
              >恢复</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域优化 -->
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改题库对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item v-if="form.id" label="题目ID">
          <el-input v-model="form.id" disabled />
        </el-form-item>
        <el-form-item label="题目分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择题目分类" style="width: 100%">
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.name"
              :value="parseInt(item.id)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="题目类型" prop="typeId">
          <el-select v-model="form.typeId" placeholder="请选择题目类型" style="width: 100%">
            <el-option
              v-for="item in typeOptions"
              :key="item.id"
              :label="item.name"
              :value="parseInt(item.id)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="题目内容" prop="title">
          <editor v-model="form.title" :min-height="192"/>
        </el-form-item>
        <el-form-item label="出题方" prop="creator">
          <el-input 
            v-model="form.creator" 
            placeholder="请输入出题方"
            clearable
            style="width: 100%"
          />
        </el-form-item>
        <!-- 修改答案选项管理部分 -->
        <el-divider content-position="left">答案选项</el-divider>
        <div class="answer-list">
          <div v-for="(answer, index) in form.answers" :key="index" class="answer-item">
            <el-row :gutter="20">
              <el-col :span="16">
                <el-form-item 
                  :label="'选项' + (index + 1)" 
                  :prop="'answers.' + index + '.content'"
                  :rules="{ required: true, message: '请输入选项内容', trigger: 'blur' }"
                >
                  <editor v-model="answer.content" :min-height="120"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="是否正确">
                  <el-select v-model="answer.isCorrect" placeholder="请选择" style="width: 100%">
                    <el-option 
                      label="正确答案" 
                      :value="0"
                    >
                      <span style="color: #67C23A">
                        <i class="el-icon-check"></i> 正确答案
                      </span>
                    </el-option>
                    <el-option 
                      label="错误选项" 
                      :value="1"
                    >
                      <span style="color: #909399">
                        <i class="el-icon-close"></i> 错误选项
                      </span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="2" class="answer-actions">
                <el-button 
                  type="danger" 
                  icon="el-icon-delete" 
                  circle 
                  @click="removeAnswer(index)"
                  title="删除此选项"
                ></el-button>
              </el-col>
            </el-row>
          </div>
        </div>
        <div class="add-answer">
          <el-button 
            type="primary" 
            icon="el-icon-plus" 
            @click="addAnswer"
            :disabled="form.answers.length >= 6"
          >添加答案选项</el-button>
          <div class="answer-tip" v-if="form.answers.length >= 6">
            <i class="el-icon-warning"></i> 最多添加6个选项
          </div>
        </div>
        <!-- 在答案选项后添加答案解析部分 -->
        <el-divider content-position="left">答案解析</el-divider>
        <el-form-item label="解析内容">
          <editor 
            v-model="form.analysis.content" 
            :min-height="192"
            v-if="form.analysis"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listQuestions, getQuestions, delQuestions, addQuestions, updateQuestions, restoreQuestions } from "@/api/question/questions";
import { listCategory } from "@/api/question/category";
import { listType } from "@/api/question/type";
import { listAnswer, addAnswer, updateAnswer } from "@/api/question/answer";
import { listAnalysis, addAnalysis, updateAnalysis } from "@/api/question/analysis";

// 定义默认表单数据
const defaultForm = {
  id: null,
  categoryId: null,
  typeId: null,
  title: null,
  creator: null,
  isDeleted: 0,
  answers: [],
  analysis: {
    content: ''
  }
};

export default {
  name: "Questions",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 题库表格数据
      questionsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        categoryId: null,
        typeId: null,
        creator: null,
        isDeleted: '0'
      },
      // 表单参数
      form: { ...defaultForm },
      // 表单校验
      rules: {
        categoryId: [
          { required: true, message: "题目分类不能为空", trigger: "change" }
        ],
        typeId: [
          { required: true, message: "题目类型不能为空", trigger: "change" }
        ],
        title: [
          { required: true, message: "题目内容不能为空", trigger: "blur" }
        ],
        creator: [
          { required: true, message: "出题方不能为空", trigger: "blur" }
        ]
      },
      // 分类选项
      categoryOptions: [],
      // 类型选项
      typeOptions: [],
      // 分类搜索加载中
      categoryLoading: false,
      // 类型搜索加载中
      typeLoading: false,
      // 添加回收站显示状态
      showDeleted: false
    };
  },
  created() {
    this.getList();
    this.getCategoryAndTypeOptions();
  },
  methods: {
    /** 查询题库列表 */
    getList() {
      this.loading = true;
      listQuestions(this.queryParams).then(response => {
        this.questionsList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
        this.questionsList = [];
        this.total = 0;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 重置表单 */
    reset() {
      this.form = { 
        ...defaultForm,
        answers: [],
        analysis: {
          content: ''
        }
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      // 保持当前回收站状态
      this.queryParams.isDeleted = this.showDeleted ? '1' : '0';
      // 重置分页参数
      this.queryParams.pageNum = 1;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加题库";
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      
      try {
        // 获取题目信息（包含了所有关联数据）
        const questionResponse = await getQuestions(id);
        console.log('题目数据:', questionResponse.data);
        
        // 设置表单数据
        this.form = {
          ...questionResponse.data,
          categoryId: questionResponse.data.categoryId,
          typeId: questionResponse.data.typeId,
          isDeleted: parseInt(questionResponse.data.isDeleted),
          // 处理答案选项数据
          answers: questionResponse.data.dtAnswers?.map(item => ({
            id: item.id,
            questionId: item.questionId,
            content: item.content,
            isCorrect: parseInt(item.isCorrect),
            isDeleted: parseInt(item.isDeleted)
          })) || [],
          // 处理答案解析数据
          analysis: {
            id: questionResponse.data.dtQuestionAnalysis?.id,
            questionId: questionResponse.data.dtQuestionAnalysis?.questionId,
            content: questionResponse.data.dtQuestionAnalysis?.content || '',
            isDeleted: parseInt(questionResponse.data.dtQuestionAnalysis?.isDeleted || '0')
          }
        };

        this.open = true;
        this.title = "修改题目";
      } catch (error) {
        this.$modal.msgError("获取数据失败");
        console.error("获取数据失败:", error);
      }
    },
    /** 提交表单 */
    submitForm() {
      this.$refs["form"].validate(async valid => {
        if (!valid) return;

        const loading = this.$loading({
          lock: true,
          text: '提交中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        try {
          let questionId;
          
          if (this.form.id) {
            // 修改题目
            await updateQuestions(this.form);
            questionId = this.form.id;

            // 处理答案选项
            if (this.form.answers && this.form.answers.length > 0) {
              const answerPromises = this.form.answers.map(answer => {
                const answerData = {
                  ...answer,
                  questionId
                };
                return answer.id ? updateAnswer(answerData) : addAnswer(answerData);
              });
              await Promise.all(answerPromises);
            }

            // 处理答案解析
            if (this.form.analysis && this.form.analysis.content) {
              const analysisData = {
                ...this.form.analysis,
                questionId,
                content: this.form.analysis.content
              };
              if (analysisData.id) {
                await updateAnalysis(analysisData);
              } else {
                await addAnalysis(analysisData);
              }
            }
          } else {
            // 新增题目
            await addQuestions(this.form);
            
            // 查询新添加的题目ID
            const searchResponse = await listQuestions({
              title: this.form.title,
              pageSize: 1,
              creator: this.form.creator,
              categoryId: this.form.categoryId,
              typeId: this.form.typeId
            });
            
            if (!searchResponse.rows || searchResponse.rows.length === 0) {
              throw new Error('获取题目ID失败');
            }
            
            questionId = searchResponse.rows[0].id;

            // 处理答案选项
            if (this.form.answers && this.form.answers.length > 0) {
              const answerPromises = this.form.answers.map(answer => ({
                content: answer.content,
                isCorrect: answer.isCorrect,
                questionId
              }));
              await Promise.all(answerPromises.map(addAnswer));
            }

            // 处理答案解析
            if (this.form.analysis && this.form.analysis.content) {
              await addAnalysis({
                content: this.form.analysis.content,
                questionId
              });
            }
          }

          loading.close();
          this.$modal.msgSuccess(this.form.id ? "修改成功" : "新增成功");
          this.open = false;
          this.getList();
        } catch (error) {
          loading.close();
          this.$modal.msgError("操作失败");
          console.error("保存失败:", error);
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除题库编号为"' + ids + '"的数据项？').then(function() {
        return delQuestions(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('question/questions/export', {
        ...this.queryParams
      }, `questions_${new Date().getTime()}.xlsx`)
    },
    /** 获取分类和类型选项 */
    async getCategoryAndTypeOptions() {
      try {
        // 并行获取分类和类型数据
        const [categoryResponse, typeResponse] = await Promise.all([
          listCategory({ pageSize: 999999 }),
          listType({ pageSize: 999999 })
        ]);

        this.categoryOptions = categoryResponse.rows || [];
        this.typeOptions = typeResponse.rows || [];
      } catch (error) {
        console.error("获取分类和类型数据失败:", error);
        this.$modal.msgError("获取数据失败");
      }
    },
    /** 处理分类搜索 */
    handleCategorySearch(query) {
      if (query) {
        this.categoryOptions = this.categoryOptions.filter(item => 
          item.name.toLowerCase().includes(query.toLowerCase())
        );
      }
    },
    /** 处理类型搜索 */
    handleTypeSearch(query) {
      if (query) {
        this.typeOptions = this.typeOptions.filter(item => 
          item.name.toLowerCase().includes(query.toLowerCase())
        );
      }
    },
    /** 切换回收站显示状态 */
    toggleRecycleBin() {
      this.showDeleted = !this.showDeleted;
      // 重置分页参数
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
      this.queryParams.isDeleted = this.showDeleted ? '1' : '0';
      // 重置选中状态
      this.ids = [];
      this.single = true;
      this.multiple = true;
      // 重新获取列表
      this.getList();
    },
    /** 添加答案选项 */
    addAnswer() {
      const newAnswer = {
        questionId: this.form.id || null,  // 设置 questionId
        content: '',
        isCorrect: 1,
        isDeleted: 0
      };
      
      if (!this.form.answers) {
        this.$set(this.form, 'answers', [newAnswer]);
      } else {
        this.form.answers.push(newAnswer);
      }
    },
    /** 移除答案选项 */
    removeAnswer(index) {
      this.$confirm('是否确认删除该选项？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.form.answers.splice(index, 1);
        this.$message({
          type: 'success',
          message: '删除成功'
        });
      }).catch(() => {});
    },
    /** 恢复按钮操作 */
    handleRestore(row) {
      const id = row.id || this.ids;
      this.$modal.confirm('是否确认恢复题目编号为"' + id + '"的数据项？').then(async () => {
        // 获取题目详细信息
        const response = await getQuestions(id);
        // 修改状态为0（正常）
        const data = {
          ...response.data,
          isDeleted: 0
        };
        // 调用修改接口
        return updateQuestions(data);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("恢复成功");
      }).catch(() => {});
    }
  }
};
</script>

<style scoped>
/* 布局相关 */
.box-card {
  margin-bottom: 16px;
  border-radius: 4px;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2f3d;
}

.action-buttons {
  float: right;
}

.action-buttons .el-button {
  margin-left: 8px;
}

.action-buttons .el-button:first-child {
  margin-left: 0;
}

.el-card {
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08) !important;
}

.el-card :deep(.el-card__header) {
  padding: 12px 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #fafafa;
}

/* 答案选项相关 */
.answer-list {
  margin: 16px 0;
}

.answer-item {
  padding: 20px;
  margin-bottom: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s;
}

.answer-item:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-color: #d4d7de;
}

/* 编辑器样式 */
.answer-item :deep(.w-e-text-container) {
  min-height: 120px !important;
  border-color: #DCDFE6;
  border-radius: 4px;
  
}

/* 工具类 */
.clearfix::after {
  content: '';
  display: table;
  clear: both;
}
</style>
